package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemCat;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public  class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Autowired
	private ItemDescMapper itemDescMapper;

	/**
	 * 利用MP机制实现商品查询
	 */
	@Override
	public EasyUITable<Item> findAll(Integer page, Integer row) {
		QueryWrapper<Item> queryWrapper=new QueryWrapper();
		queryWrapper.orderByDesc("updated");
		IPage<Item> ipage=new Page<>(page,row);
		ipage = itemMapper.selectPage(ipage,queryWrapper);
		int total=(int)ipage.getTotal();
		List<Item> itemList=ipage.getRecords();
		return new EasyUITable<>(total,itemList);
	}

	@Transactional //控制事务
	@Override
	public void saveItem(Item item, ItemDesc itemDesc) {
		//1.默认商品为上架状态
		item.setStatus(1);
		itemMapper.insert(item);//先入库才有主键
		//MP支持,用户操作可以实现自动主键回显功能

		//知识点:id应该如何获取?
		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);
	}

	@Override
	@Transactional
	public void deleteItem(Long[] ids) {
		List<Long> list= Arrays.asList(ids);
		itemMapper.deleteBatchIds(list);
		itemDescMapper.deleteBatchIds(list);
	}

	@Override
	@Transactional
	public void updateItem(Item item,ItemDesc itemDesc) {
		item.setUpdated(new Date());
		itemMapper.updateById(item);

		UpdateWrapper<ItemDesc> updateWrapper=new UpdateWrapper<>();
		updateWrapper.eq("item_id",item.getId());
		itemDescMapper.update(itemDesc,updateWrapper);
	}

	@Override
	public void updateStatus(Integer status, Long[] ids) {
		Item item=new Item();
		item.setStatus(status);
		List<Long> list=Arrays.asList(ids);
		UpdateWrapper<Item> updateWrapper=new UpdateWrapper<>();
		updateWrapper.in("id",list);
		itemMapper.update(item,updateWrapper);
	}

	@Override
	public ItemDesc findItemDescById(Long itemId) {
		return itemDescMapper.selectById(itemId);
	}

	/*@Override
	public EasyUITable<Item> findAll(Integer page, Integer row) {
		int startIndex=(page-1)*row;
		List<Item> rows=itemMapper.findAll(startIndex,row);
		int total=itemMapper.getCount();
		return new EasyUITable<>(total,rows);
	}*/
}
